<?php

namespace Frieza\Modules\Newtag\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\NewTag\Tag as dbTag;
use Doraemon\model\NewTag\TagPackage;
use Doraemon\model\NewTag\OperationTagContent;
use Doraemon\model\NewTag\PackageApplication;


class TagPackageController extends Controller
{

    const PAGE_SIZE = 20;

    const OPERATE_TYPE_ADD = 1;
    const OPERATE_TYPE_DELETE = 2;


    public function list(Request $request, Content $content)
    {
        $params = $request->all();

        return $content
            ->header('标签分包列表')
            ->breadcrumb(
                [
                    'text' => '标签分包列表',
                    'url'  => '/newtag/packagelist'
                ]
            )
            ->body(self::listAction($params));
    }


    private static function listAction($params)
    {

        $data = TagPackage::getList();
        $gridModel = new pGridDataModel($data, count($data), []);


        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $applications = PackageApplication::getList();
            $application_infos = [];
            if($applications && is_array($applications)) {
                foreach($applications as $application_info) {
                    $application_infos[$application_info['id']] = $application_info['application_name'];
                }
            }

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->tools(function ($tools) {
                $tools->append("<a href='application' class='btn btn-sm btn-success' style='float: right;'><i class='fa fa-save'>&nbsp;&nbsp;编辑分包用途</i></a>");
            });

            $grid->column('id');
            $grid->column('description', '标签包描述')->editable()->width(200);
            $grid->column('application_id', '用途')->replace($application_infos)->width(100);
            $grid->column('extra_info', '额外信息')->width(200);

            $grid->column('tags', '包含的标签')->display(function() {
                return explode(',', $this->tags);
            })->label('default')->width(500);
            $grid->column('addtime', '操作时间')->display(function() {
                return "添加时间:".$this->addtime."<br/>最后修改时间".$this->edittime;
            });
            $grid->column('admin_id', '最后操作人')->display(function() {
                return Admin::user()->find($this->admin_id)->name;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions){
                //$actions->disableEdit();
                $actions->disableDelete();
                $actions->prepend('<a class="fa reload-data fa-building-o" href="/admin/newtag/packagelist/edittags/'. $actions->row->id . '" >编辑包中标签</a><br>');
            });

        });

        return $listGrid;
    }

    //修改包中标签
    public function editTags(Request $request, Content $content, $id)
    {
        $old_tag_ids = [];
        $tags = dbTag::getAllByWhere([
            'tag_status' => dbTag::STATUS_NORMAL,
            'ORDER' => [
                'tag_sort' => 'ASC'
            ],
        ], ['id', 'tag', 'deep', 'parent_id']);

        $package_info = TagPackage::getInfoById($id);
        if($package_info && is_array($package_info)) {
            $old_tag_ids = array_filter(explode(',', $package_info['tag_ids']));
            $description = $package_info['description'];
        }

        if($tags && is_array($tags)) {
            foreach($tags as &$tag) {
                $tag['text'] = $tag['tag'];
                $tag['href'] = '/admin/newtag/list?tag='.$tag['tag'];
                if($old_tag_ids && is_array($old_tag_ids)) {
                    if(in_array($tag['id'], $old_tag_ids)) {
                        $tag['state'] = ['expanded' => true, 'checked' => true];
                    }
                }
            }
        }

        $tags_arr = $this->getArr($tags);

        $tags_json = json_encode($tags_arr, JSON_UNESCAPED_UNICODE);

        Admin::script($this->listScript($tags_json, $id, true, 2));


        return $content
            ->header('为标签包：- '.$description.' -选择标签')
            ->breadcrumb(
                [
                    'text' => '标签包列表',
                    'url'  => '/newtag/packagelist'
                ],
                [
                    'text' => '修改标签包内容',
                    'url'  => '/newtag/packagelist'
                ]
            )
            ->row("<a href='javascript:;' class='btn btn-sm btn-adn show_all ' style='float: right;margin-left:5px;'>
<i class='fa fa-delicious'>&nbsp;&nbsp;全部展开</i></a> 
<a href='javascript:;' class='btn btn-sm btn-adn hide_all' style='float: right;margin-left:5px;'><i class='fa fa-delicious'>&nbsp;&nbsp;全部折叠</i></a><br>")
            ->row("<div id='tree'></div>");
    }

    //修改标签包描述
    public function editDescription(Request $request)
    {
        $params = $request->all();
        $data[$params['name']] = $params['value'];
        $data['edittime'] = date('Y-m-d H:i:s', time());
        $data['admin_id'] = Admin::user()->id;
        $rs = TagPackage::updateById($data, $params['pk']);
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    //添加页面
    public function create(Request $request, Content $content, $id = 0)
    {
        //获取用途信息
        $applications = PackageApplication::getList();
        $options = [];
        if($applications && is_array($applications)) {
            foreach($applications as $application_info) {
                $options[$application_info['id']] = $application_info['application_name'];
            }
        }
        if($id == 0) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = TagPackage::getInfoById($id);
            $extra_info_arr = json_decode($data['extra_info'], true);

            $extra_info_mid = [];
            if($extra_info_arr && is_array($extra_info_arr)) {
                foreach($extra_info_arr as $key=>$value) {
                    $extra_info_mid[] =  $key.':'.$value;
                }
            }
            $extra_info_str = implode(',', $extra_info_mid);
            $data['extra_info'] = $extra_info_str;
            $form = new Form($data);
            $form->hidden('id');

        }

        $form->text('description', '标签包描述')->required('此字段必填');
        $form->select('application_id', '标签包用途')->options($options)->required('用途必选');
        $form->textarea('extra_info', '额外属性')->help('配置时不同属性用英文逗号分隔,每个属性的键值用英文冒号分隔,属性名请与对应研发沟通确认。示例：   get_num:3,order:2,is_show:0');
        $form->action('/admin/newtag/packagelist/save');
        return $content
            ->header('标签分包列表')
            ->breadcrumb(
                [
                    'text' => '标签包列表',
                    'url'  => '/newtag/packagelist'
                ],
                [
                    'text' => '添加标签包',
                    'url'  => '/newtag/packagelist/create'
                ]
            )
            ->body($form);
    }

    //保存
    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $extra_info_arr = [];
        $extra_info = explode(',', $params['extra_info']);
        if($extra_info && is_array($extra_info)) {
            foreach($extra_info as $info) {
                $info_arr = array_filter(explode(':', $info));
                if($info_arr && is_array($info_arr)) {
                    $extra_info_arr[$info_arr[0]] = $info_arr[1];
                }

            }
        }
        if(!isset($params['id'])) {
            $data = [
                'description' => $params['description'],
                'application_id' => $params['application_id'],
                'extra_info' => json_encode($extra_info_arr, JSON_UNESCAPED_UNICODE),
                'addtime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            $rs = TagPackage::addData($data);

        } else {
            $data = [
                'description' => $params['description'],
                'application_id' => $params['application_id'],
                'extra_info' => json_encode($extra_info_arr, JSON_UNESCAPED_UNICODE),
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            $rs = TagPackage::updateById($data, $params['id']);
        }

        if($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/newtag/packagelist')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'
            ]);
            return redirect('/admin/newtag/packagelist')->with(compact('error'));
        }

    }

    //删除
    public function del(Request $request, $id)
    {
        $rs = TagPackage::updateById([
            "edittime" => date('Y-m-d H:i:s', time()),
            "package_status" => TagPackage::STATUS_DELETE
        ], $id);
        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }


    //标签树
    public function treeList(Request $request, Content $content)
    {
        $tags = dbTag::getAllByWhere([
            'tag_status' => dbTag::STATUS_NORMAL,
            'ORDER' => [
                'tag_sort' => 'ASC'
            ],
        ], ['id', 'tag', 'deep', 'parent_id']);

        //获取统计信息
        $week = date('Y-W', time() - 86400*7);
        $counts = OperationTagContent::getContentCountsByTags($week);

        if($tags && is_array($tags)) {
            foreach($tags as &$tag) {
                $tag['text'] = $tag['tag']."     ". (string) $counts[$tag['tag']];
                $tag['href'] = '/admin/newtag/list?tag='.$tag['tag'];
            }
        }

        $tags_arr = $this->getArr($tags);

        $tags_json = json_encode($tags_arr, JSON_UNESCAPED_UNICODE);

        Admin::script($this->treeListScript($tags_json));


        return $content
            ->header('标签树')
            ->breadcrumb(
                [
                    'text' => '标签列表',
                    'url'  => '/newtag/list'
                ]
            )
            ->row("<a href='javascript:;' class='btn btn-sm btn-adn show_all ' style='float: right;margin-left:5px;'>
<i class='fa fa-delicious'>&nbsp;&nbsp;全部展开</i></a>
 <a href='javascript:;' class='btn btn-sm btn-adn hide_all' style='float: right;margin-left:5px;'><i class='fa fa-delicious'>&nbsp;&nbsp;全部折叠</i></a>
 <br>")
            ->row("<div id='treelist'></div>");

    }

    private function treeListScript($tags_json)
    {
        return <<<SCRIPT
        
        $('#treelist').treeview({
            data:$tags_json,
            levels: 0,
            enableLinks:true,
            
        });
            
            
        //全部展开
        $('.show_all').unbind('click').click(function(){
            $('#treelist').treeview( 'expandAll' , {levels: 10, data:$tags_json});
           
        });
        
        //全部折叠
        $('.hide_all').unbind('click').click(function(){
            $('#treelist').treeview( 'collapseAll', {data:$tags_json});
        });
        
        
SCRIPT;
    }


    private function listScript($tags_json, $id = 0, $show_checkbox = false, $level = 0)
    {
        return <<<SCRIPT
        
        $('#tree').treeview({
            data:$tags_json,
            showCheckbox:$show_checkbox,
            levels: $level,
            enableLinks:true,
            onNodeChecked: function(event, node) { //选中节点                      
                 var selectNodes = getChildNodeIdArr(node); //获取所有子节点
                 var selectTexts = getNodeTitleArr(node);
                 var selectIds = getNodeIdArr(node);
                 console.log(selectIds);
                 $.ajax({
                     type:"post",
                     url:$id+"/submit",
                     data:{id:$id,tags:JSON.stringify(selectTexts),tag_ids:JSON.stringify(selectIds),type:1},
                     success:function(data){
                        layer.alert(data['data']);
                     }
                 });
                 if (selectNodes) { //子节点不为空，则选中所有子节点
                     $('#tree').treeview('checkNode', [selectNodes, { silent: true }]);
                 }
                 var parentNode = $("#tree").treeview("getNode", node.parentId);
                 //子节点全选取消对父节点的影响
                 //setParentNodeCheck(node);
             },
             onNodeUnchecked: function(event, node) { //取消选中节点
                 var selectNodes = getChildNodeIdArr(node); //获取所有子节点
                 var selectTexts = getNodeTitleArr(node);
                 var selectIds = getNodeIdArr(node);
                 console.log(selectIds);
                 $.ajax({
                     type:"post",
                     url:$id+"/submit",
                     data:{id:$id,tags:JSON.stringify(selectTexts),tag_ids:JSON.stringify(selectIds),type:2},
                     success:function(data){
                        layer.alert(data['data']); 
                     }
                 });
                 
                 
                 if (selectNodes) { //子节点不为空，则取消选中所有子节点
                     $('#tree').treeview('uncheckNode', [selectNodes, { silent: true }]);
                 }
             }
            
        });
        
        
        function getChildNodeIdArr(node) {
             var ts = [];
             if (node.nodes) {
                 for (x in node.nodes) {
                     ts.push(node.nodes[x].nodeId);
                     if (node.nodes[x].nodes) {
                         var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
                         for (j in getNodeDieDai) {
                             ts.push(getNodeDieDai[j]);
                         }
                     }
                 }
             } else {
                 ts.push(node.nodeId);
             }
             return ts;
        }
         
         function getNodeTitleArr(node) {
             var ts = [];
             ts.push(node.text);
             if (node.nodes) {  
                 for (x in node.nodes) {
                     ts.push(node.nodes[x].text);
                     if (node.nodes[x].nodes) {
                         var getNodeDieDai = getNodeTitleArr(node.nodes[x]);
                         for (j in getNodeDieDai) {
                             ts.push(getNodeDieDai[j]);
                         }
                     }
                 }
             }
             return ts;
         }
         
         function getNodeIdArr(node) {
             var ts = [];
             ts.push(node.id);
             if (node.nodes) {
                 for (x in node.nodes) {
                     ts.push(node.nodes[x].id);
                     if (node.nodes[x].nodes) {
                         var getNodeDieDai = getNodeIdArr(node.nodes[x]);
                         for (j in getNodeDieDai) {
                             ts.push(getNodeDieDai[j]);
                         }
                     }
                 }
             }
             return ts;
         }
         
 
         function setParentNodeCheck(node) {
             var parentNode = $("#tree").treeview("getNode", node.parentId);
             if (parentNode.nodes) {
                 var checkedCount = 0;
                 for (x in parentNode.nodes) {
                     if (parentNode.nodes[x].state.checked) {
                         checkedCount ++;
                     } else {
                         break;
                     }
                 }
                 if (checkedCount === parentNode.nodes.length) {
                     $("#tree").treeview("checkNode", parentNode.nodeId);
                     setParentNodeCheck(parentNode);
                 }
             }
         }
            
            
        //全部展开
        $('.show_all').unbind('click').click(function(){
            $('#tree').treeview( 'expandAll' , {levels: 10, data:$tags_json});
        });
        
        //全部折叠
        $('.hide_all').unbind('click').click(function(){
            $('#tree').treeview( 'collapseAll', {data:$tags_json});
        });
        
        
SCRIPT;
    }

    public function editTagsSubmit(Request $request, $id)
    {

        $request = $request->all();
        $package_id = $request['id'];
        $tags = json_decode($request['tags'], true);
        $tag_ids = json_decode($request['tag_ids'], true);
        $type = $request['type'];
        $package_info = TagPackage::getInfoById($package_id);

        if($package_info && is_array($package_info)) {
            $rs = false;
            //旧包含标签id
            $old_tags = explode(',', $package_info['tags']);
            //旧包含标签名
            $old_tag_ids = explode(',', $package_info['tag_ids']);

            if ($type == self::OPERATE_TYPE_ADD) {
                $new_tags = array_filter(array_merge($old_tags, $tags));
                $new_tag_ids = array_filter(array_merge($old_tag_ids, $tag_ids));

                $rs = TagPackage::updateById([
                    "edittime" => date('Y-m-d H:i:s', time()),
                    "admin_id" => Admin::user()->id,
                    "tags" => implode(',', array_unique($new_tags)),
                    "tag_ids" => implode(',', array_unique($new_tag_ids))
                ], $package_id);


            } else if ($type == self::OPERATE_TYPE_DELETE) {

                $new_tags = array_filter(array_diff($old_tags, $tags));
                $new_tag_ids = array_filter(array_diff($old_tag_ids, $tag_ids));

                $rs = TagPackage::updateById([
                    "edittime" => date('Y-m-d H:i:s', time()),
                    "admin_id" => Admin::user()->id,
                    "tags" => implode(',', array_unique($new_tags)),
                    "tag_ids" => implode(',', array_unique($new_tag_ids))
                ], $package_id);

            }
            if($rs) {
                return [
                    'code' => 200,
                    'data' => '自动保存成功'
                ];
            }
        }
        return [
            'code' => 400,
            'data' => '自动保存失败'
        ];

    }


    //从pid依次判断
    public function getArr($arr,$pid=0){
        $child = $this->find_son($arr,$pid); //找当前元素的子集
        foreach($child as $k => $v){
            $tree = $this->getArr($arr,$v['id']);
            if(null != $tree){
                $child[$k]['nodes']= $tree;
            }
        }
        return $child;
    }
    //找当前子集的方法
    public function find_son(&$arr,$id){
        $child = [];
        foreach($arr as $k => $v){
            if($v['parent_id'] == $id){
                $child[] = $v;
            }
        }
        return $child;
    }



    //分包用途列表
    public function applicationList(Content $content)
    {
        return $content
            ->header('分包用途列表')
            ->breadcrumb(
                [
                    'text' => '分包列表',
                    'url'  => '/newtag/packagelist'
                ],
                [
                    'text' => '分包用途列表',
                    'url'  => '/newtag/application'
                ]
            )
            ->body(self::applicationListAction());
    }

    private static function applicationListAction()
    {

        $data = PackageApplication::getList();

        $gridModel = new pGridDataModel($data, count($data));


        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->expandFilter();
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->disableCreateButton();

            $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                $create->text('application_name', '用途名称');
                $create->text('application_comment', '用途备注');
            });

            $grid->column('id');
            $grid->column('application_name', '用途名称')->editable()->width(100);
            $grid->column('application_comment', '用途备注')->editable()->width(400);

            $grid->column('addtime', '时间')->display(function() {
                return "创建时间：".$this->addtime."<br/>最后自改时间".$this->edittime;
            });
            $grid->column('admin_id', '最后操作人')->display(function() {
                return Admin::user()->find($this->admin_id)->name;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();

            });

        });

        return $listGrid;
    }

    //选项提交
    public function applicationSaveSubmit(Request $request, $id = 0)
    {
        $request = $request->all();
        //dump($request);die;

        $data = [
            "admin_id" => Admin::user()->id,
            "application_status" => PackageApplication::STATUS_ON
        ];

        if(isset($id) && $id) {
            //修改
            $data[$request['name']] = $request['value'];
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = PackageApplication::updateById($data, $id);
        } else {
            //添加
            $data["application_name"] = $request['application_name'];
            $data["application_comment"] = $request['application_comment'];
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = PackageApplication::addData($data);
        }

        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }


    //删除
    public function delApplication($id)
    {
        $applications = array_unique(TagPackage::getApplications());

        if(in_array($id, $applications)) {
            return response()->json([
                'status' => false,
                'message' => "删除失败,此用途已被标签包关联，请先解除关联再删除",
            ]);
        }

        $rs = PackageApplication::updateById([
            "edittime" => date('Y-m-d H:i:s', time()),
            "application_status" => PackageApplication::STATUS_OFF,
            "admin_id" => Admin::user()->id
        ], $id);

        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }

    }






}
